package fy.erp.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.json.JSONArray;
import org.json.JSONObject;

import fy.config.FyConfig;
import fy.util.DBUtil;

public class QueryKeMuDuanCompanyDao {

	private static int count = 0;

	private static String result;
	
	private static String arrayResult;

	public static String getResult() {
		return result;
	}

	public static String getArrayResult() {
		return arrayResult == null ? "[]" :  arrayResult;
	}

	public static String query() {
		if (result == null || arrayResult == null || count > 20) {
			result = null;
			count = 0;
			Connection conn = null;
			PreparedStatement pst = null;
			ResultSet rs = null;

			boolean success = false;

			try {
				conn = DBUtil.connect(FyConfig.getERP_DB_CONFIG());

				pst = conn
						.prepareStatement("SELECT flex_value 公司代码, description 公司说明  FROM apps.fnd_flex_values_vl WHERE flex_value_set_id = 1009698 and flex_value <> '0' and flex_value<>'T' order by flex_value asc");

				rs = pst.executeQuery();
				JSONObject jo = new JSONObject();
				JSONArray ja = new JSONArray();
				while (rs.next()) {
					String name = rs.getString(2);
					String id = rs.getString(1);
					jo.put(name, id);
					JSONArray child = new JSONArray();
					child.put(name);
					child.put(id);
					ja.put(child);
				}
				result = jo.toString();
				arrayResult = ja.toString();
				success = true;
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				DBUtil.close(rs, pst, conn);
			}
			return success ? result : "2";
		} else {
			count++;
			return result;
		}
	}
}
